package com.powernode.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.powernode.domain.Permission;
import com.powernode.domain.User;
import com.powernode.mapper.PermissionMapper;
import com.powernode.mapper.RoleMapper;
import com.powernode.mapper.UserMapper;
import com.powernode.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 走自己的认证流程
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据帐号查询用户信息
        User user = userMapper.selectUserByLoginAct(username);
        // 判断用户是否存在
        if (ObjUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("用户名或密码有误");
        }

        // 查询登录用户的角色集合
        Set<String> roleList = roleMapper.selectRoleListByUserId(user.getId());

        // 查询当前用户的菜单集合
        Set<Permission> menuList = permissionMapper.selectMenuListByUserId(user.getId());

        // 查询当前用户的操作权限集合
        Set<String> permissionList = permissionMapper.selectPermissionListByUserId(user.getId());
        // 创建Security框架能够认识的安全用户对象
        SecurityUser securityUser = SecurityUser.builder()
                .id(user.getId())
                .loginAct(user.getLoginAct())
                .loginPwd(user.getLoginPwd())
                .name(user.getName())
                .phone(user.getPhone())
                .email(user.getEmail())
                .accountNoExpired(user.getAccountNoExpired())
                .credentialsNoExpired(user.getCredentialsNoExpired())
                .accountNoLocked(user.getAccountNoLocked())
                .accountEnabled(user.getAccountEnabled())
                .createTime(user.getCreateTime())
                .createBy(user.getCreateBy())
                .lastLoginTime(user.getLastLoginTime())
                .permissionList(permissionList)
                .roleList(roleList)
                .menuList(menuList)
                .build();
        return securityUser;
    }
}
